package com.my.lock.v12;

import java.util.concurrent.atomic.AtomicInteger;

public class Semaphore {
    private AtomicInteger semaphore;
    private int max;

    public Semaphore(int max) {
        this.max = max;
        this.semaphore = new AtomicInteger(max);
    }

    public boolean increment() {
        while (true) {
            int value = this.semaphore.get();
            if (value >= this.max) {
                return false;
            } else {
                if (this.semaphore.compareAndSet(value, value + 1)) {
                    return true;
                }
            }
        }
    }

    public boolean decrement() {
        while (true) {
            int value = this.semaphore.get();
            if (value <= 0) {
                return false;
            } else {
                if (this.semaphore.compareAndSet(value, value - 1)) {
                    return true;
                }
            }

        }
    }

    public AtomicInteger getSemaphore() {
        return semaphore;
    }

    public int getMax() {
        return max;
    }
}
